<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem">
      <template v-slot:customTableHeader>
        <tabs :tabsList="tabsList" @switchTab="switchTab"></tabs>
      </template>
    </tablePaging>
    <el-dialog v-model="courseVisible" :title="'重命名'" @close="requestEdit.id = null, requestEdit.name = '',ruleFormRef.clearValidate()">
      <el-form :rules="rules" ref="ruleFormRef" :model="requestEdit" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input maxlength="30" v-model="requestEdit.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="courseVisible = false">取 消</el-button>
          <el-button type="primary" @click="courseConfirm(ruleFormRef)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上架失败 -->
    <el-dialog title="上架返回结果" v-model="resultReject" width="540px">
      <div>
        <el-table :data="rejectList"
          :header-cell-style="{ 'text-align': 'center', 'background': '#fff', 'height': '44px' }"
          :cell-style="{ 'text-align': 'center', 'height': '44px' }" style="max-height:440px;overflow-y:scroll">
          <el-table-column label="失败原因" prop="message"></el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer ">
          <el-button type="primary" @click="resultReject = false">
            确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import tabs from '@/views/common/component/tabs'
import tablePaging from '@/views/common/component/table-paging'
import fileImport from '@/views/common/component/fileImport'
import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from "element-plus";
import { tableItem, operationItem, bankFlagUPApi, courseAddApi, configBankApi, nameBankApi, courseDelApi, enableBankTypeListApi } from './const.jsx'
import { download } from "@/utils/request";
const importVisible = ref(false)
const courseVisible = ref(false)
const ruleFormRef = ref('')
const requestEdit = reactive({
  id: null,
  name: ''
})
const { proxy } = getCurrentInstance();

const router = useRouter()
const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})

const importItem = reactive({
  downUrl: '',//文件下载地址
  fileDown() { },//自定义文件下载方法 如果传入下载地址会失效 如果都不传会返回一个fileDown函数 自己@fileDown接收
  downTitle: '',//下载标题 默认1、模板下载
  downButtonText: '',//下载按钮 下载
  upButtonText: '',//上传按钮 上传
  upTitle: '',//上传标题 默认2、表格上传
  downName: null
})
onMounted(() => { initTabsList(); initSubOption(); })
//
const courseConfirm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (!valid) { return }
    const { name, id } = requestEdit
    nameBankApi({ name, id }).then(res => {
      ElMessage.success('操作成功'); courseVisible.value = false; tableItem.pageInfo.paging()
    })
  })

}
tableItem.btnArray[0].handle = (row) => {
  router.push({
    path: '/modules/question/allQuestion/detailsQuestion',
    query: { courseParentId: row.id, type: 'pages', publishFlag: row.publishFlag }
  })
}
// 重命名
tableItem.btnArray[1].handle = (row) => {
  requestEdit.name = row.name || ''
  requestEdit.id = row.id
  courseVisible.value = true
}
// 上架
const rejectList = ref([])
const resultReject = ref(false)
tableItem.btnArray[2].handle = (row) => {
  bankFlagUPApi({ id: row.id, publishFlag: 1 }).then((res) => {
    ElMessage.success(res.msg || "操作成功");
    tableItem.pageInfo.paging();
  }).catch((rej) => {
    rejectList.value = []
    if(!rej.rows||rej.rows.length==0){return}
    rej.rows.map((item) => {
      rejectList.value.push({
        message: item
      })
    })
    resultReject.value = true
  });
}
// 删除
tableItem.btnArray[4].handle = (row) => {
  proxy.$modal.confirm("确定删除" + row.name).then(() => {
    courseDelApi(row.id).then(res => {
      ElMessage.success('操作成功'); tableItem.pageInfo.paging()
    })
  })
}
operationItem.menuArray[0].handle = () => {
  router.push({
    path: '/modules/question/allQuestion/questionAdd',
    query: { courseParentId: tableItem.pageInfo.request.courseParentId }
  })
}
// operationItem.menuArray[0].handle = () => {
//   importVisible.value = true
// }
//
const onSuccess = (file) => { }
const onError = (file) => { }
const switchTab = (row, index) => {
  tableItem.pageInfo.request.courseParentId = row.id || null
  tableItem.pageInfo.paging()
}
const tabsList = ref([])
// 类别
const initTabsList = () => {
  courseAddApi({ levelNum: 2, parentId: null, disableFlag: null }).then(res => {
    tabsList.value = res.rows
    if (!res.rows && res.rows.length == 0) { return }
    tableItem.pageInfo.request.courseParentId = res.rows[0].id
    tableItem.pageInfo.paging()
    initCourseBankTypeOption()
  })
}
// 题库类型
const initCourseBankTypeOption = () => {
  enableBankTypeListApi({ courseId: tableItem.pageInfo.request.courseParentId }).then(res => { operationItem.SearchItem[3].options = res.rows || [] })
}
// 科目
const initSubOption = () => {
  // courseAddApi({ "levelNum": 3, "parentId": null, }).then(res => {
  //   operationItem.SearchItem[1].options = res.rows || []
  //   console.log(res.rows);
  //   // if (saveOptions.subOption.length == 0) { return }
  // })
}
const handleClick = (tab, event) => {
  console.log(tab, event)
}
const tablePagingFather = ref('')
const input = ref('')
const buttonList = reactive([

],)

//处理批量删除相关代码
//#region
const selectedRow = ref([])

//每次选中项变化时，记录选中项数组，并且判断选中项是否可以批量删除（已经上架的不能删除，所以禁用按钮）
tableItem.selectChange = (row) => {
  //构建需要删除的id列表
  selectedRow.value = row.map( (item) => {
    return item.id
  } )

  //控制批量删除按钮是否可用，初始状态不可用，因为没有选择
  if (!row || row.length <= 0) {
    operationItem.menuArray[2].disabled = true
  }

  //若有题库已经上架了，按钮状态不可用
  for (let i = 0; i < row.length; i++) {
    if ((row[i].closeButton + '').includes('删除')) {
      operationItem.menuArray[2].disabled = true
      return ;
    } else {
      operationItem.menuArray[2].disabled = false //别忘了恢复按钮状态，不然一直不可用
    }
  }
}

//处理点击批量删除
operationItem.menuArray[2].handle = () => {
  proxy.$modal.confirm("确定批量删除?").then(() => {
    courseDelApi(selectedRow.value).then(res => {
      ElMessage.success('操作成功');
      tableItem.pageInfo.paging()
    })
  })
}
//导出
operationItem.menuArray[1].handle = () => {
  let url = '/bank/question/export'
  let fileName = '导出题库'
  let requestData = {...tableItem.pageInfo.request}
  download(url, requestData, fileName, {}, {})
}
//#endregion
</script>

<style lang="scss" scoped>
:deep(.el-dialog:not(.is-fullscreen)) {
  // width: 556px;
}
</style>
